var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var app = express();


var vertoken = require('./utils/token');
var expressJWT = require('express-jwt');
// 引入跨域插件 必须放在所有请求前面
const cors = require('cors');
// 解决跨域
app.use(cors());

// 静态资源
app.use(express.static(path.join(__dirname, 'img_Upload')));
app.use(express.static(path.join(__dirname, 'img_Sweiper')));
app.use(express.static(path.join(__dirname, 'homeImg')));
app.use(express.static(path.join(__dirname, 'img_Dynamic')));



// 不验证token的接口
var noTokenRouterUrl = ['/users/addUsers', "/users/login", "/swiper/list", "/imageTab/list", "/homeImg/list", "/users/admin/login", "/users/getadminlist", "/searchList/search", "/homeImg/searchImg", "/searchList/search/list", "/dynamic/list", "/dynamic/listDetails", "/message/dynamic/list", "/message/give/list"]


// 解析token获取用户信息
app.use(function (req, res, next) {
  var token = req.headers['authorization'];

  if (token == undefined) {
    return next();
  } else {
    vertoken.verToken(token).then((data) => {
      req.data = data;
      return next();
    }).catch((error) => {
      return next();
    })
  }
});
//验证token
app.use(expressJWT({
  secret: 'jiangzichen_token_express_server',//自定义秘钥 
  algorithms: ["HS256"]
}).unless({
  path: noTokenRouterUrl//除了这些地址，其他的URL都需要验证
}));

// 错误处理
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message
  res.locals.error = req.app.get('env') === 'development' ? err : {}
  // render the error page
  res.status(err.status || 500)

  if (err.status == 401) {
    res.send(httpRequest.untoken())
  } else if (err.status == 404) {
    res.send(httpRequest.notFound())
  } else {
    res.send({ code: err.status, data: {}, msg: err.status })
  }
})



// 导入接口
var usersRouter = require('./routes/users'); //用户
var uploadsRouter = require('./routes/uploads/index')//上传文件
var swiperRouter = require('./routes/swiper/index')//轮播图
var imageTabRouter = require('./routes/imageTab/index')//图片分类
var homeImgRouter = require('./routes/home/index')//图片
var searchRouter = require('./routes/search/index')//搜索
var dynamicRouter = require('./routes/dynamic/index')//动态
var messageRouter = require('./routes/message/index')//消息通知
var AdministratorRouter = require('./routes/Administrator/index')//申请管理员



// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 定义接口
app.use('/users', usersRouter);
app.use('/uploadsFiles', uploadsRouter);
app.use('/swiper', swiperRouter);
app.use('/imageTab', imageTabRouter);
app.use('/homeImg', homeImgRouter);
app.use('/searchList', searchRouter);
app.use('/dynamic', dynamicRouter);
app.use('/message', messageRouter);
app.use('/Administrator', AdministratorRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
